﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using AjaxChatService.Models;
using Newtonsoft.Json.Linq;

namespace AjaxChatService.YahooMessenger
{
    public class GetContactsHelper
    {
        //public YMAuthentication Authentication { get; set; }

        //public string SessionId;

        public IEnumerable<YMContact> ExecuteRequest(string sessionId, string credentials)
        {
            //  Create the HTTP URL
            var uri = "http://" + "rcore1.messenger.yahooapis.com" +
                            YMConstants.ContactListManagementUrl + "?sid=" + sessionId + "&fields=%2Bpresence" + "&"
                            + credentials;

            WebRequest request = WebRequest.Create(uri);
            request.ContentType = "application/json; charset=utf-8";

            var responseStr = HttpUtils.SendHttpGet(request, null);
            JObject result = JObject.Parse(responseStr);

            if (result == null)
                throw new MessengerException(MessengerException.UNKNOWN_SERVER_ERROR, "Unknown server error");

            return UnserializeJSONResponseParameters(result);
        }

        private IEnumerable<YMContact> UnserializeJSONResponseParameters(JObject result)
        {
            List<YMContact> lst = new List<YMContact>();
            JArray contacts = (JArray)result["contacts"];
            foreach (JObject jObj in contacts)
            {
                //var contact = (JObject)token;
                var jtoken = jObj["contact"];
                string id = jtoken["id"].ToString();
                string uri = jtoken["uri"].ToString();
                int status = (int)jtoken["presence"]["presenceState"];

                YMContact contact = new YMContact
                                    {
                                        Id = id,
                                        Uri = uri,
                                        Status = status,
                                        Avatar = YMConstants.AvatarUrl + id
                                    };

                lst.Add(contact);
            }

            return lst;
        }
    }
}